/*
 * @Descripttion:
 * @Author: 张明尧
 * @Date: 2020-09-21 08:52:21
 * @LastEditTime: 2020-09-21 11:30:15
 */
/**
 * @Author : ZiQin Zhai
 * @Date : 2020/8/31 18:01
 * @Version : 1.0
 * @Last Modifined by : ZiQin Zhai
 * @Last Modifined time : 2020/8/31 18:01
 * @Description 用于安装运行于h5端的插件
 * */
import Vue from 'vue';
import rootTemplate from '../components/template/index';

Vue.config.productionTip = false;
Vue.config.devtools = true;

/**
 * 处理路由信息，将/路由重定向到router信息的第一个路由地址中
 */
function transformRootPath(router = []) {
  const path = router.length && router[0].path;
  if (path) {
    router.unshift({
      path: '/',
      redirect: path,
    });
  }
  return router;
}

/**
 * 装载方法
 * @param routers 项目的路由信息
 * @param pluginCode 插件编码
 * @param beforeInstall 在挂载到H5项目之前执行的方法
 */
export default function (routers, { pluginCode }, { beforeInstall } = {}) {
  window.__useRouter = true;
  /**
   * 在h5中定义了_vue的全局对象，app当中没有
   */
  if (!window.plus && window._vue) {
    __webpack_public_path__ = JE.pluginUtil.getRuntimePublicPath();
    // 增加插件标识
    function addFlag(_routers, isRoot = true) {
      if (Array.isArray(_routers)) {
        _routers.forEach((router) => {
          if (JE.isObject(router.meta)) {
            router.meta.isPlugin = true;
            router.meta.pluginCode = pluginCode;
          } else {
            router.meta = {
              isPlugin: true,
              pluginCode,
            };
          }
          if (router.children) {
            router.children = addFlag(router.children, false);
          }
          isRoot && (router.path = router.path.slice(1));
        });
      }
      return _routers;
    }
    JE.pluginUtil.setPluginRouter(pluginCode, addFlag(routers), {
      beforeInstall,
    });
  } else {
    const myRuntimePublicPath = '../';
    __webpack_public_path__ = myRuntimePublicPath;
    beforeInstall && beforeInstall(Vue);
    Vue.use(VueRouter);
    new Vue({
      router: new VueRouter({
        routes: transformRootPath(routers),
      }),
      render: h => h(rootTemplate),
    }).$mount('#app');
  }
}
